#!/usr/bin/env python
# encoding: utf-8

import urllib,urllib2
import json,commands,sys,os
dx = commands.getoutput("ip a|grep eth0|sed -n 2p|awk '{print $2}'|awk -F/ '{print $1}'")
lt = commands.getoutput("ip a|grep eth0|sed -n 3p|awk '{print $2}'|awk -F/ '{print $1}'")

xl={}
xl['默认']=dx
xl['电信']=dx
xl['联通']=lt

public=dict(login_email="695001606@qq.com",
            login_password="************",
            format="json",)
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'}


def getdomainID():
    try:
        params=public.copy()
        params['domain']='puzzled.com'
        data=urllib.urlencode(params)
        req = urllib2.Request('https://dnsapi.cn/Domain.Info',data,headers=headers)
        response = urllib2.urlopen(req,timeout=5)
    except urllib2.URLError,e:
        print e.reason
        print "网络超时无法打开网站"
    else:
        myjson=json.loads(response.read())
        return myjson['domain']['id']

def createdomain(domainID):
    params=public.copy()
    params['record_type']='A'
    params['domain_id']=domainID
    params['sub_domain']='s'+sys.argv[2]+'.'+sys.argv[1]+'dcj'
    for k,v in xl.items():
        params['record_line'] = k
        params['value']=v
        req = urllib2.Request('https://dnsapi.cn/Record.Create',headers=headers,data=urllib.urlencode(params))
        response=urllib2.urlopen(req)
        myjson=json.load(response)
        if int(myjson['status']['code']) == 1:
            print k+'    '+ params['sub_domain']+'.'+'puzzled.com'+ '  '+ v+'   '+ '解析成功'
        elif int(myjson['status']['code']) == 31:
            print k+'    '+params['sub_domain']+'.'+'puzzled.com 解析失败'
            print "\033[35m code:31 域名已经解析过存在A记录 \033[m"
        else:
            print "错误响应代码 myjson['status']['code']"

if __name__=='__main__':
    if len(sys.argv) == 3:
        domainID=getdomainID()
        createdomain(domainID)
#        os.remove('./dns.py')
    else:
        print "python dns.py 平台  区号"
